import Vue from 'vue'
// 导入Vuex并注册到vue
import Vuex from 'vuex'

Vue.use(Vuex);

import layerutils from "../system/utils/layerutils";

// 创建全局变量
var store = {};
try {
    const user = JSON.parse(localStorage.getItem("user") || "{}");
    const topTagArr = JSON.parse(localStorage.getItem("topTagArr") || "[]");
    const activeTagIndex = localStorage.getItem("activeTagIndex") || "";
    const activeMenu = localStorage.getItem("activeMenu") || "";
    const breadArrStr = localStorage.getItem("breadArr") || "";
    var breadArr = [];
    if(breadArrStr) {
        breadArr = breadArrStr.split(",");
    }

    // 创建全局的store对象
    store = new Vuex.Store({
        state: {
            user: user,
            // 面包屑
            breadArr:breadArr,

            // tabtags顶部标签
            topTagArr:topTagArr,
            // 激活的标签页
            activeTagIndex:activeTagIndex,
            // 当前激活的菜单id
            activeMenu:activeMenu,
            // 所有的菜单
            menuList:[]

        },
        mutations: {
            dealUser(state,user){
                // 当前用户
                state.user = user;
                // 缓存起来
                localStorage.setItem("user",JSON.stringify(user));
            },
            dealBreadArr(state,menuPath){
                let breadArr = [];
                if(menuPath){
                    let menuPathArr = menuPath.split("-");
                    menuPathArr.forEach(item=>{
                        breadArr.push(item);
                    })
                }
                // 展开当前窗口
                state.breadArr = breadArr;
                // 缓存起来
                localStorage.setItem("breadArr",breadArr);
            },
            dealActiveTagIndex(state,activeTagIndex){
                // 展开当前窗口
                state.activeTagIndex = activeTagIndex;
                // 缓存起来
                localStorage.setItem("activeTagIndex",activeTagIndex);
            },
            dealActiveMenu(state,activeMenu){
                // 展开当前窗口
                state.activeMenu = activeMenu;
                // 缓存起来
                localStorage.setItem("activeMenu",activeMenu);
            },
            dealMenuList(state,menuList){
                // 所有菜单
                state.menuList = menuList;
                // 缓存起来
                localStorage.setItem("menuList",JSON.stringify(menuList));
            },
            clearStateParams(state){
                // 清楚缓存
                localStorage.clear();
                state.user =  {};
                state.breadArr = "";
                state.topTagArr = [];
                state.activeTagIndex = "";
                state.activeMenu = "";
                state.menuList = [];
            }
        },
        getters: {}
    });
} catch (e) {
    // 出现异常，清理所有的缓存
    // 获取缓存数据出现异常，
    layerutils.showError("获取缓存数据失败，请重新登录！",200,()=>{
        // 清理所有的缓存数据
        this.$store.commit("clearStateParams");
    });

}


export default store;
